/**
 * FollowCamera2D
 * a57633056a
 * Mon Feb 06 2023 16:07:55 GMT+0800 (中国标准时间)
 * FollowCamera2D.ts
 * FollowCamera2D
 * db://assets/script/framework/components/camera/FollowCamera2D.ts
 * https://docs.cocos.com/creator/3.7/manual/zh/
 */
import * as cc from 'cc';
import { Loger } from '../../loger/Loger';
const { ccclass, property, menu } = cc._decorator;

@ccclass('FollowCamera2D')
@menu('扩展组件/FollowCamera2D')
export class FollowCamera2D extends cc.Component {

    @property({ type: cc.Node, tooltip: "跟随节点" })
    targetNode: cc.Node = null;
    @property({ type: cc.CCFloat, tooltip: "插值跟随时的速度" })
    speed: number = 10;
    @property({ type: cc.CCFloat, tooltip: "距离多远时开始跟随" })
    offsetLength: number = 50;

    targetUITrans: cc.UITransform
    parentUITrans: cc.UITransform

    private _following: boolean = false;
    private _offsetY: number
    onLoad() {
        this.parentUITrans = this.node.parent.getComponent(cc.UITransform);
        this._offsetY = this.node.position.y
    }

    start() {
        this.init();
    }

    init(target?: cc.Node, speed?: number) {
        this.targetNode = target || this.targetNode;
        this.speed = speed || this.speed;
        if (!this.targetNode) {
            return;
        }
        this.targetUITrans = this.targetNode.getComponent(cc.UITransform);
    }

    lateUpdate(dt: number) {
        if (!this.targetNode) {
            return;
        }
        this._lerpFollow(dt);
    }

    /**插值自动跟随 */
    private _lerpFollow(dt) {
        const worldPos = this.targetUITrans.convertToWorldSpaceAR(cc.Vec3.ZERO)
        const nodePos = this.parentUITrans.convertToNodeSpaceAR(worldPos);
        let nodePosV2 = cc.v2(nodePos.x, nodePos.y + this._offsetY);
        let selfPos = cc.v2(this.node.position.x, this.node.position.y);
        const dir = nodePosV2.subtract(selfPos)
        const len = dir.length();

        if (len > this.offsetLength) {
            this._following = true;
        }
        if (!this._following) {
            return;
        }
        if (len <= 1) {
            this._following = false;
            // Loger.log("Follow len <= 1 y:", nodePos.y);
            this.node.setPosition(nodePos.x, nodePos.y + this._offsetY, this.node.position.z);
            return;
        }
        // Loger.log("lerping y:", selfPos.y);
        //插值计算
        selfPos.lerp(selfPos.clone().add(dir), dt * this.speed);
        //移动节点
        this.node.setPosition(selfPos.x, selfPos.y, this.node.position.z);

    }

}